<?php
class Register_Controller extends Template_Controller {

	public $template = 'client/index';
	
    public function __construct()
    {
        parent::__construct();
		//Css
        $this->template->css = $this->site['theme_url'].'register/register.css';
        //View
        $this->get_view();
    }
    
	function _get_submit()
	{
		if($this->session->get('error_msg'))
			$this->template->content->error_msg = $this->session->get('error_msg');
		if($this->session->get('warning_msg'))
			$this->template->content->warning_msg = $this->session->get('warning_msg');
		if($this->session->get('success_msg'))
			$this->template->content->success_msg = $this->session->get('success_msg');
		if($this->session->get('info_msg'))
			$this->template->content->info_msg = $this->session->get('info_msg');
		if($this->session->get('frm'))			
			$this->template->content->mr = $this->session->get('frm');		
	}
	
	private function _list_state()
	{
		$model = new State_Model();
		return $model->get();
	}
	
    public function index()
    {	
        $this->template->content = new View('register/frm');
        
        $this->template->content->list_state = $this->_list_state();
        
        $this->_get_submit();
    }
    
    private function _set_form($form)
    {	
		$record['customers_username'] = $form['txt_username'];		
		$record['customers_email'] = $form['txt_email'];
		$record['customers_pass'] = $form['txt_pass'];
		$record['customers_type'] = $form['chk_type'];
		$record['customers_name'] = $form['txt_fullname'];
		$record['customers_firstname'] = $form['txt_firstname'];
		$record['customers_lastname'] = $form['txt_lastname'];		
		$record['customers_address'] = $form['txt_address'];
		$record['customers_address2'] = $form['txt_address2'];
		$record['customers_city'] = $form['txt_city'];
		$record['customers_state'] = $form['sel_state'];
		$record['customers_zipcode'] = $form['txt_zipcode'];
		$record['customers_phone'] = $form['txt_phone'];
		$record['customers_fax'] = $form['txt_fax'];
		$record['customers_status'] = 1;			
		return $record;
	}
    
    function _get_record()
    {
    	$form = array
	    (
	        'txt_username' => '',	        
	        'txt_email' => '',
			'txt_pass' => '',
			'chk_type' => '',			
			'txt_fullname' => '',
			'txt_firstname' => '',
	        'txt_lastname' => '',      
	        'txt_address' => '',
	        'txt_address2' => '',
	        'txt_city' => '',
	        'sel_state' => '',
	        'txt_zipcode' => '',
			'txt_phone' => '',
	        'txt_fax' => '',	        
	    );
	    
	    $errors = $form;
		
		if($_POST)
    	{
    		$post = new Validation($_POST);
    		
			$post->pre_filter('trim', TRUE);
			$post->add_rules('txt_username','required');			
			$post->add_rules('txt_pass','required');
			$post->add_rules('txt_email','required','email');
			$post->add_callbacks('txt_username',array($this, '_unique_user'));
			$post->add_callbacks('txt_email',array($this, '_unique_email'));
			
			$form = arr::overwrite($form, $post->as_array());
			$form = $this->_set_form($form);
			if($post->validate())
 			{ 				
 				return $form; 				
			} else {
				$this->session->set_flash('frm',$form);
				$errors = arr::overwrite($errors, $post->errors('register_validation'));
				$error_msg = '';
				foreach($errors as $id => $name) if($name) $error_msg .= '<br>'.$name;
				$this->session->set_flash('error_msg',$error_msg);
				
				url::redirect('register');
				die();
			}
        }
    }
	
	//check username exists 
    public function _unique_user(Validation $array, $field)
	{
	   // check the database for existing records
	   $user_exists = (bool) ORM::factory('customer')->where('customers_username', $array[$field])->count_all();	 
	   if ($user_exists)
	   {
		   // add error to validation object
		   $array->add_error($field, '_unique_user');		   		  
	   }
	}
	
	// check email exists
	public function _unique_email(Validation $array, $field)
	{
	   // check the database for existing records
	   $email_exists = (bool) ORM::factory('customer')->where('customers_email', $array[$field])->count_all();	 
	   if ($email_exists)
	   {
		   // add error to validation object
		   $array->add_error($field, '_unique_email');		  
	   }
	}
	
    private function send_email($record)
    {
    	//Use connect() method to load Swiftmailer
		$swift = email::connect();
		 
		//From, subject
		$from = $this->site['site_email'];
		$subject = 'Register '.$this->site['site_name'];
		
		//HTML message
		$path = 'application/views/email_tpl/register.tpl';
		$fi = fopen($path,'r+');
		$html_content = file_get_contents($path); 	
		//Replate content	
		$name = $record['customers_firstname'].' '.$record['customers_lastname'];		
		$html_content = str_replace('#name#',$name,$html_content);		
		$html_content = str_replace('#username#',$record['customers_username'],$html_content);		
		$html_content = str_replace('#sitename#',$this->site['site_name'],$html_content);		
		$html_content = str_replace('#password#',$record['customers_pass'],$html_content);
		fclose($fi);

		//Build recipient lists
		$recipients = new Swift_RecipientList;
		$recipients->addTo($record['customers_email']);
		 
		//Build the HTML message
		$message = new Swift_Message($subject, $html_content, "text/html");
		 
		if($swift->send($message, $recipients, $from)){
			url::redirect('register/thanks');
			die();
		} else {
			
		}		 
		// Disconnect
		$swift->disconnect();
    }
    
    public function sm()
    {
    	$record = $this->_get_record();
		
    	if($record)
    	{
    		//Mailing
			$resultmalling = ORM::factory('mailing');			
			$resultmalling->mailing_email = $record['customers_email'];
			if($record['customers_type'] ==1){
				$type=2;
			} else {
				$type=1;
			}
    		$resultmalling->mailing_malgrp_id = $type;
			$resultmalling->mailing_active = '1';
			$malling = $resultmalling->save();
	
			//Customer
    		$query = $this->db->insert('customers', $record);
			$id = $query->insert_id();
			
			if($id){
				$this->send_email($record);
			}
    	}    	
    	url::redirect('register');
		die();
    }
    
    public function thanks()
    {
    	$this->template->content = new View('register/thanks');
    }
}
?>